<template>
  <div>
    <a-row class="playedu-main-body">
      <a-col :span="24">
        <div class="float-left mb-24">
          <BackBartment :title="title || '线上课学员'" />
        </div>
        <div class="float-left j-b-flex mb-24">
          <div class="d-flex">
            <PerButton
              type="primary"
              text="重置学习记录"
              class="mr-16"
              :icon="null"
              p="course"
              @click="delItem"
              :disabled="selectedRowKeys.length === 0"
            />
          </div>
          <div class="d-flex">
            <div class="d-flex mr-24">
              <a-typography-text>学员姓名：</a-typography-text>
              <a-input
                v-model:value="name"
                allow-clear
                style="width: 160px"
                placeholder="请输入姓名关键字"
              />
            </div>
            <div class="d-flex mr-24">
              <a-typography-text>学员邮箱：</a-typography-text>
              <a-input
                v-model:value="email"
                allow-clear
                style="width: 160px"
                placeholder="请输入学员邮箱"
              />
            </div>
            <div class="d-flex">
              <a-button class="mr-16" @click="resetList">重 置</a-button>
              <a-button type="primary" @click="handleSearch">查 询</a-button>
            </div>
          </div>
        </div>
        <div class="float-left">
          <a-table
            :row-selection="rowSelection"
            :data-source="list"
            :loading="loading"
            :pagination="paginationProps"
            :row-key="(record) => record.id"
          >
            <a-table-column title="学员">
              <template #customRender="{ record }">
                <div class="d-flex">
                  <a-image
                    style="border-radius: 50%"
                    :preview="false"
                    :width="40"
                    :height="40"
                    :src="record.avatar == -1 ? memberDefaultAvatar : resourceUrl[record.avatar]"
                  />
                  <span class="ml-8">{{ record.name }}</span>
                </div>
              </template>
            </a-table-column>

            <a-table-column title="邮箱">
              <template #customRender="{ record }">
                <span>{{ record.email }}</span>
              </template>
            </a-table-column>

            <a-table-column title="部门">
              <template #customRender="{ record }">
                <div class="float-left">
                  <span v-if="userDepIds[record.id]">
                    <span v-for="(item, index) in userDepIds[record.id]" :key="index">
                      {{ departments[item] }}{{ index === userDepIds[record.id].length - 1 ? '' : '、' }}
                    </span>
                  </span>
                </div>
              </template>
            </a-table-column>

            <a-table-column title="课程进度">
              <template #customRender="{ record }">
                <span>
                  已完成课时：
                  {{ (records[record.id] && records[record.id].finished_count) || 0 }} /
                  {{ (records[record.id] && records[record.id].hour_count) || course?.class_hour }}
                </span>
              </template>
            </a-table-column>

            <a-table-column title="第一次学习时间">
              <template #customRender="{ record }">
                <span v-if="perRecords[record.id]">
                  {{ dateFormat(perRecords[record.id].created_at) }}
                </span>
                <span v-else-if="hourCount[record.id]">
                  {{ dateFormat(hourCount[record.id]) }}
                </span>
                <span v-else>-</span>
              </template>
            </a-table-column>

            <a-table-column title="学习完成时间">
              <template #customRender="{ record }">
                <span v-if="records[record.id] && records[record.id].finished_at">
                  {{ dateFormat(String(records[record.id].finished_at)) }}
                </span>
                <span v-else>-</span>
              </template>
            </a-table-column>

            <a-table-column title="学习进度">
              <template #customRender="{ record }">
                <span :class="getProgressClass(record)">
                  {{ getProgress(record) }}%
                </span>
              </template>
            </a-table-column>
          </a-table>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import { Modal, message } from 'ant-design-vue';
import BackBartment from '@/components/Common/back-bar.vue';
import PerButton from '@/components/Common/permission-button.vue';
import { dateFormat } from '@/utils';
import { course as CourseApi } from '@/api';
import memberDefaultAvatar from '@/assets/thumb/avatar.png';

const { confirm } = Modal;
const route = useRoute();

// 响应式数据
const list = ref([]);
const course = ref(null);
const records = ref({});
const hourCount = ref({});
const userDepIds = ref({});
const departments = ref({});
const perRecords = ref({});
const refresh = ref(false);
const page = ref(1);
const size = ref(10);
const total = ref(0);
const loading = ref(true);
const name = ref('');
const email = ref('');
const idCard = ref('');
const selectedRowKeys = ref([]);
const resourceUrl = ref({});
const title = ref(route.query.title || '');

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const courseId = Number(route.params.courseId);
    const res = await CourseApi.courseUser(courseId, page.value, size.value, '', '', name.value, email.value, idCard.value);
    
    total.value = res.data.total;
    list.value = res.data.data;
    hourCount.value = res.data.user_course_hour_user_first_at;
    records.value = res.data.user_course_records;
    perRecords.value = res.data.per_user_earliest_records;
    resourceUrl.value = res.data.resource_url;
    course.value = res.data.course;
    departments.value = res.data.departments;
    userDepIds.value = res.data.user_dep_ids;
  } catch (err) {
    console.error('获取学员列表失败:', err);
    message.error('获取学员列表失败');
  } finally {
    loading.value = false;
  }
};

// 计算进度
const getProgress = (record) => {
  const recordData = records.value[record.id];
  if (recordData) {
    return Math.floor((recordData.finished_count / recordData.hour_count) * 100);
  } else if (hourCount.value[record.id]) {
    return 1;
  } else {
    return 0;
  }
};

// 计算进度样式类
const getProgressClass = (record) => {
  const progress = getProgress(record);
  return progress >= 100 ? 'c-green' : 'c-red';
};

// 处理分页变化
const handlePageChange = (current, pageSize) => {
  page.value = current;
  size.value = pageSize;
};

// 分页配置
const paginationProps = reactive({
  current: page,
  pageSize: size,
  total: total,
  showSizeChanger: true,
  onChange: handlePageChange,
  onShowSizeChange: handlePageChange,
});

// 行选择配置
const rowSelection = reactive({
  onChange: (selectedKeys) => {
    selectedRowKeys.value = selectedKeys;
  },
  selectedRowKeys: selectedRowKeys
});

// 重置列表
const resetList = () => {
  page.value = 1;
  size.value = 10;
  list.value = [];
  name.value = '';
  email.value = '';
  idCard.value = '';
  refresh.value = !refresh.value;
};

// 处理搜索
const handleSearch = () => {
  page.value = 1;
  refresh.value = !refresh.value;
};

// 删除学员学习记录
const delItem = () => {
  if (selectedRowKeys.value.length === 0) {
    message.error('请选择学员后再重置');
    return;
  }
  
  confirm({
    title: '操作确认',
    icon: () => h('ExclamationCircleFilled'),
    content: '确认重置选中学员学习记录？',
    centered: true,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        await CourseApi.destroyCourseUser(Number(route.params.courseId), selectedRowKeys.value);
        message.success('清除成功');
        resetList();
        selectedRowKeys.value = [];
      } catch (error) {
        console.error('重置学习记录失败:', error);
        message.error('重置学习记录失败');
      }
    },
  });
};

// 监听参数变化
watch(
  [() => route.params.courseId, () => refresh.value, () => page.value, () => size.value],
  () => {
    getList();
  },
  { immediate: true }
);
</script>

<style scoped>
.playedu-main-body {
  padding: 24px;
}

.float-left {
  float: left;
}

.mb-24 {
  margin-bottom: 24px;
}

.j-b-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.d-flex {
  display: flex;
  align-items: center;
}

.mr-16 {
  margin-right: 16px;
}

.mr-24 {
  margin-right: 24px;
}

.ml-8 {
  margin-left: 8px;
}

.c-green {
  color: #52c41a;
}

.c-red {
  color: #ff4d4f;
}
</style>